Skip to main content
Version: 1.0.0

createVariantDocument

Function Name: createOrUpdateVariantDocument

Author: Domenico Cerone Creation Date: 25/09/2025
Last Reviewer: Domenico Cerone

Trigger: Called by populateVariantFromSku and populateVariantFromExcel

Purpose: Manages creation and updating of documents in the 'Variants' Firestore collection from mapped JSON data generated by populateVariantFromSku. Handles complete variant lifecycle with automatic tag management, brand integration, and comprehensive field mapping.

Detailed Functionalityโ€‹

This component function handles the complete Variants collection management with a sophisticated 3-step workflow for both new variants and existing variant updates. Includes thread-safe tag creation system and brand normalization to ensure data consistency in high-concurrency scenarios.

1. DOCUMENT EXISTENCE CHECKโ€‹

  • Searches in 'Variants' collection for document with skuModel equal to provided value
  • If EXISTS โ†’ updates only necessary fields (STEP 3)
  • If NOT EXISTS โ†’ creates new complete document (STEP 2)

2. NEW DOCUMENT CREATIONโ€‹

  • Creates document with complete base structure
  • Populates only mapped fields from JSON, leaves others empty
  • Uses Firestore auto-generated ID
  • Sets status = "Incompleto"

3. EXISTING DOCUMENT UPDATEโ€‹

  • Updates only fields that come from mapped JSON
  • Maintains all other existing fields unchanged
  • Updates lastUpdate with current timestamp

Fields Populated from Mapped JSONโ€‹

Directly Mapped Fieldsโ€‹

  • skuModel โ† skuModel (main identifier)
  • eanCode โ† eanCode
  • frameColor โ† frameColor
  • lensesColor โ† lensesColor
  • glassesName โ† glassesName
  • mainBrandRef โ† Brand ID (find/create in MainBrands collection)
  • upcCode โ† upcCode
  • batch โ† batch (value from CatalogOrder or input parameter)
  • productRef โ† Parent Products document ID
  • catalogOrdersRef โ† CatalogOrder ID that generated the variant
  • poster โ† poster (view 00 - main frontal)
  • poster2 โ† poster2 (view 07 - lateral angle)
  • poster3 โ† poster3 (view 02 - frontal detail)
  • poster4 โ† poster4 (view 01 - alternative angle)

Timestamp Fields (with conversion)โ€‹

  • lastUpdate โ† current timestamp (Date object)
  • skuReleaseDate โ† skuReleaseDate (if present, Date object)
  • skuEndDate โ† skuEndDate (if present, Date object)
  • advStartDate โ† advStartDate (if present, Date object)
  • advEndDate โ† advEndDate (if present, Date object)

Boolean Fieldโ€‹

  • isADV โ† isADV (converted from "YES"/"NO" to boolean)

Size Object (all fields as strings)โ€‹

  • size.bridge โ† bridge
  • size.frameWidth โ† frameWidth
  • size.lensHeight โ† lensHeight
  • size.lensWidth โ† lensWidth
  • size.size โ† size
  • size.templeLength โ† templeLength
  • size.frontHeight โ† frontHeight
  • size.hingeToHinge โ† hingeToHinge
  • size.lensCircumference โ† lensCircumference
  • size.lensAngle โ† lensAngle
  • size.phantoscopicAngle โ† phantoscopicAngle

Special Arraysโ€‹

  • list_size_color_tags โ† [frameColor tag ID, size tag ID] (find/create in Tags collection)
  • list_images โ† list_images (array of objects with view and url)

Tag Management Systemโ€‹

The function automatically creates/finds tags in the Tags collection:

Frame Color Tagsโ€‹

  • Group: "Frame Color"
  • Type: "frameColor"
  • GroupOrder: 11
  • Name: frameColor value (e.g., "BLACK", "BURGUNDY 2")

Size Tagsโ€‹

  • Group: "Size"
  • Type: "size"
  • GroupOrder: 10
  • Name: size value (e.g., "54", "99")

Base Document Structureโ€‹

All other fields maintain default values:

  • assignedTo: ""
  • assignmentDate: ""
  • dataTaken: false
  • id: "" (auto-generated by Firestore)
  • loadingId: ""
  • mainModel: false
  • modelPriority: ""
  • modelViewerUrl: ""
  • modify_model: { rejectCount: "", requestCount: "", status: "" }
  • posterNoBackground: ""
  • primaryFrameColorHex: ""
  • primaryLensesColorHex: ""
  • priority: 0
  • productRef: ""
  • refLogVariant: ""
  • secondaryFrameColorHex: ""
  • secondaryLensesColorHex: ""
  • status: "Incompleto"
  • templeColor: ""
  • urlDE: ""
  • urlES: ""
  • urlFR: ""
  • urlGlobal: ""
  • urlGlobalComplete: ""
  • urlGlobalCompleteSize: 0
  • urlGlobalSize: 0
  • urlProductPage: ""
  • urlUsdz: ""
  • urlUsdzComplete: ""
  • urlUsdzCompleteSize: 0
  • urlUsdzSize: 0
  • variantCode: ""
  • list_notes: []

Function Parametersโ€‹

/**
* @param {Object} mappedJsonData - Mapped JSON data from populateVariantFromSku
* @param {string} requestId - Request ID for logging
* @param {string} batch - Variant batch assignment (optional)
* @param {string} productRef - Parent Products document ID (optional)
* @param {string} catalogOrdersRef - CatalogOrder ID that generated the variant (optional)
* @returns {Promise<Object>} Operation result with details
*/

Date Field Conversionโ€‹

Timestamp fields are automatically converted from various formats to JavaScript Date objects:

Supported Input Formatsโ€‹

  • Number: Unix timestamp in milliseconds
  • String: ISO 8601 date string (e.g., "2025-08-01T02:00:00")
  • Empty/null: Remains empty

Automatic Conversionโ€‹

  • All date fields are converted to JavaScript Date objects
  • Empty or invalid dates remain as empty strings
  • Current timestamp used as fallback for conversion errors

Image Managementโ€‹

The function handles image arrays from the mapped JSON:

list_images Structureโ€‹

[
{
"view": "00",
"url": "https://firebasestorage.googleapis.com/.../image_00.jpg?token=xxx"
},
{
"view": "01",
"url": "https://firebasestorage.googleapis.com/.../image_01.jpg?token=yyy"
},
{
"view": "02",
"url": "https://firebasestorage.googleapis.com/.../image_02.jpg?token=zzz"
}
]

Poster Fieldsโ€‹

  • poster: Main frontal view (00)
  • poster2: Lateral angle (07)
  • poster3: Frontal detail (02)
  • poster4: Alternative angle (01)

Response Structureโ€‹

Success Responseโ€‹

{
"operation": "create",
"documentId": "auto_generated_variant_id",
"skuModel": "20637008650QT",
"success": true,
"message": "New Variants document created for SKU 20637008650QT"
}

Error Responseโ€‹

{
"operation": "error",
"documentId": null,
"skuModel": "UNKNOWN",
"success": false,
"message": "Error in Variants document management: Missing skuModel",
"error": "skuModel missing in mapped data"
}

Brand Integrationโ€‹

The function integrates with the brand management system:

  • Automatically finds or creates brands in MainBrands collection
  • Uses normalized brand names according to business rules
  • Handles brand ID mapping and reference management
  • Logs brand operations for debugging and monitoring

Logging and Monitoringโ€‹

Comprehensive logging system for operation tracking:

  • Document Operations: Create/update operations with IDs
  • Brand Management: Brand find/create operations
  • Tag Management: Tag find/create operations for frame colors and sizes
  • Error Handling: Detailed error logging with context
  • Performance: Operation timing and success/failure tracking

CatalogOrder Integrationโ€‹

When called from populateVariantFromSku, the function:

  • Receives `catalogOrdersRef` parameter with CatalogOrder ID
  • Links variant to originating catalog order
  • Enables traceability from variant back to source order
  • Supports batch processing workflows

Brand Normalization Systemโ€‹

The function includes automatic brand normalization to ensure consistent brand naming across all collections.

Brand Mapping Rulesโ€‹

  • Hugo brands: "HUGO" โ†’ "HUGO EYEWEAR"
  • Boss brands: "HUGO BOSS", "BOSS ORANGE" โ†’ "BOSS EYEWEAR"
  • Carrera brands: "CARRERA BY JIMMYCHOO", "CARRERA BIKE", "CARRERA SNOW", "CARRERA DUCATI" โ†’ "CARRERA"
  • Polaroid brands: "POLAROID ANCILLARIES", "POLAROID KIDS", "POLAROID STAYSAFE" โ†’ "POLAROID"
  • Smith brands: "SMITH FASHION & ACC.", "SMITH BIKE HELMETS", "SMITH SNOW", "SMITH BIKE GOGGLES", "PRIVATE LABEL SMITH", "SUNCLOUD" โ†’ "SMITH OPTICS"
  • Other brands: Remain unchanged

Thread-Safe Tag Systemโ€‹

The function utilizes thread-safe tag creation functions to prevent duplicates:

  • findOrCreateTag() - Creates frame color and size tags with automatic deduplication โ†’ Calls findOrCreateTagThreadSafe() from tagUtils for mutex-based synchronization
  • Prevents duplicate Tags documents when processing multiple variants simultaneously

Tag Creation Process:

  • Frame Color tags: group="Frame Color", type="frameColor", groupOrder=11
  • Size tags: group="Size", type="size", groupOrder=10
  • Thread-safe creation with exclusive locks per tag combination
  • Automatic cleanup of expired locks (10 minutes timeout)